//
//  ViewController.m
//  myhuibao
//
//  Created by lijun on 13-2-4.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//
#import <QuartzCore/QuartzCore.h>
#import "RestaurantDetailViewController.h"
#import "BookViewController.h"
#import "CommentCell.h"
#import "SBJson.h"
#import "config.h"
#import "DB.h"
#import<CoreLocation/CoreLocation.h>
#import<MapKit/MapKit.h>
#import "ASPin.h"
#import "LoginViewController.h"
#import "OMGToast.h"
#import "LoadMoreCell.h"
#import "DishListViewContrller.h"
#import "CardDetailViewController.h"
#import "UpdateHeaderViewController.h"
#import "TicketMerchantViewController.h"
#import "RequestLoadingView.h"

//#import "CLMAlertView.h"
@interface RestaurantDetailViewController (){
}

@end

@implementation RestaurantDetailViewController
@synthesize btBack;
@synthesize btnRestaurant;
@synthesize btnRemark;
@synthesize btnMap;
@synthesize svMain;
@synthesize sliderLabel;
@synthesize distance;
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
//    [self addBasicView];
    pageIndex=1;
    [self initScrollView];
    
    iDishCount=0;
    dicImage=[[NSMutableDictionary alloc] initWithCapacity:30];

    [self startRequest];
}

- (void)startRequest
{
    // [loadingView setActivityViewColor:[UIColor blueColor]];
    if (!loadingView) {
        
        loadingView = [[RequestLoadingView alloc]
                       initRequestLoadingView:self
                       queueFinishSelector:nil
                       viewFrame:LoadingViewFrame];
    }
    
    [self getMerchant:_merchantId];
    [self getComment:_merchantId];
    [self getDish:_merchantId];
    
    [loadingView addRequestToQueue:reqSearch];
    [loadingView addRequestToQueue:reqComment];
    [loadingView addRequestToQueue:reqDish];
    
    [loadingView startRequestQueue];
    
}
-(void)viewWillAppear:(BOOL)animated
{
        if(self.view.tag==1)
        {
            [OMGToast showWithText:@"该会员卡已关闭" bottomOffset:100];
            self.view.tag=0;
        }
}
- (void)viewDidUnload
{
    [self setBtnRestaurant:nil];
    [self setBtnRemark:nil];
    [self setBtnMap:nil];
    [self setSvMain:nil];
    [self setSliderLabel:nil];
    [self setBtBack:nil];
    [self setLbAvgConsume:nil];
    [self setLbTitle:nil];
//    [self setDoBook:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title=@"我的惠宝";
    }
    return self;
}
- (void) getMerchant:(int) merchantId
{
    //异步请求
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?merchantID=%d&merchantType=%d",url_detail,merchantId,_merchantType]] ;
    reqSearch = [ASIHTTPRequest requestWithURL:url];
    isSearchFinished = false;
    [reqSearch setShouldAttemptPersistentConnection:NO];
    [reqSearch setDelegate: self];
    
    if (!loadingView.bFirstRequest)
    {
        [reqSearch startAsynchronous];
    }
    

    
    btBack.userInteractionEnabled = false;
    
}
- (void) getComment:(int) merchantId
{
    //异步请求
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?merchantID=%d&pageIndex=%d&merchantType=%d",url_commentList,_merchantId,pageIndex,_merchantType]] ;
    reqComment = [ASIHTTPRequest requestWithURL:url];
    isCommentFinished = false;
    [reqComment setShouldAttemptPersistentConnection:NO];
    [reqComment setDelegate: self];
    [reqComment setDidFinishSelector:@selector(finishComment:)];
    
    if(!loadingView.bFirstRequest)
    {
        [reqComment startAsynchronous];
    }
}

- (void) getDish:(int) merchantId
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?merchantID=%d&pageIndex=%d",url_dishList,_merchantId,pageIndex]] ;
    reqDish = [ASIHTTPRequest requestWithURL:url];
    [reqDish setShouldAttemptPersistentConnection:NO];
    [reqDish setDelegate: self];
    [reqDish setDidFinishSelector:@selector(finishDish:)];
    
    if(!loadingView.bFirstRequest)
        [reqDish startAsynchronous];


}

- (void)finishDish:(ASIHTTPRequest *)request
{
    NSString *jsonStr = [request responseString];
    
    NSDictionary *dic = [jsonStr JSONValue];
    tableDataArrayDish = [dic valueForKey:@"data"];
    iDishCount = [tableDataArrayDish count];
    if(iDishCount>0)
    {
        view1.ImageDishExample.hidden=YES;
        view1.lbAddImage.hidden=YES;
        for(int i=0;i<iDishCount;i++)
        {
            if(i==5)
            {
                break;
            }
                UIImageView *view=[[UIImageView alloc] init];
                NSString *strImage=[NSString stringWithFormat:@"%@%@%@",url_image,[[tableDataArrayDish objectAtIndex:i] objectForKey:@"picturePath"],[[tableDataArrayDish objectAtIndex:i] objectForKey:@"pictureName"]];
                view.frame=CGRectMake(4+i*65, 20, 60, 45);
                view.image=[UIImage imageNamed:@"placeholder.png"];
                UILabel *label=[[UILabel alloc] init];
                label.frame=CGRectMake(4+i*65, 70, 60, 10);
                label.text=[[tableDataArrayDish objectAtIndex:i] objectForKey:@"name"];
                label.font=[UIFont fontWithName:@"Helvetica" size:10];
                label.textAlignment = UITextAlignmentCenter;
                [view1.vDish addSubview:view];
                [view1.vDish addSubview:label];
                [dicImage setObject:view forKey:strImage];
        }
        //NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(downloadImage) object:nil];
        //[[[NSOperationQueue alloc]init] addOperation:op];
        [NSThread detachNewThreadSelector:@selector(downloadImage) toTarget:self withObject:nil];
    }
    else
    {
        view1.btnDishMore.hidden=YES;
    }
}

-(void)downloadImage
{
    for(NSString *strImage in dicImage)
    {
        NSURL *imageUrl = [NSURL URLWithString:[strImage stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
        UIImageView* view=[dicImage objectForKey:strImage];
        UIImage *img=[UIImage imageWithData:imageData];
        if(img)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                view.image=img;
            });
        }
    }
}

- (void)finishComment:(ASIHTTPRequest *)request
{
    isCommentFinished = true;
    NSString *jsonStr = [request responseString];
    
    NSDictionary *dic = [jsonStr JSONValue];
    tableDataArray = [dic valueForKey:@"data"];
    returnCount = [tableDataArray count];

    [view2.tbComment reloadData];
    [Config setExtraCellLineHidden:view2.tbComment];
}
//下面是两个代理函数,当数据请求成功时会调用requestFinished，请求失败时（如网络问题或服务器内部错误）会调用requestFailed
- (void)requestFinished:(ASIHTTPRequest *)request
{
    isSearchFinished = true;
    // Use when fetching text data
    NSString *jsonStr = [request responseString];
    NSMutableDictionary *dic = [[jsonStr JSONValue] valueForKey:@"data"];
    if((NSNull *)dic != [NSNull null]){
//        NSLog(@"%@",dic);
        btBack.userInteractionEnabled = true;

        //插入最近浏览表
        //[dic setObject:[NSNumber numberWithInt:_merchantType ] forKey:@"typeID"];
        [DB addLatestView:dic];
//        DB *db = [DB alloc];
//        [db addLatestView:dic];
        merchant = [dic copy];
        //详情页面
        if([dic valueForKey:@"AVGCONSUME"] != [NSNull null])
            _lbAvgConsume.text = [NSString stringWithFormat:@"人均消费：%@",[dic valueForKey:@"AVGCONSUME"]];
        else
            _lbAvgConsume.text = @"";
        if(distance !=NULL)
            view1.lbDistance.text=[NSString stringWithFormat:@"距离：%@",distance];
        else
            view1.lbDistance.hidden = true;
        if([dic valueForKey:@"PREFERENCE"] != [NSNull null])
            view1.lbPreference.text=[ dic valueForKey:@"PREFERENCE"];
        else
            view1.lbPreference.text=@"";
        if([dic valueForKey:@"IS_PARK"] != [NSNull null] && [[dic valueForKey:@"IS_PARK"] intValue]==1){
            view1.vPark.hidden=false;
        }else{
            view1.vPark.hidden=true;
            view1.vBox.frame = view1.vPark.frame;
        }
        if([dic valueForKey:@"IS_BOX"] != [NSNull null] && [[dic valueForKey:@"IS_BOX"] intValue]==1)
            view1.vBox.hidden=false;
        else
            view1.vBox.hidden=true;
        
        view1.lbName.text= [dic valueForKey:@"NAME"];
        NSString *cuisineName = [dic valueForKey:@"CUISINE_NAME"];
        if(_merchantType==1)
        {
             if([dic valueForKey:@"CUISINE_NAME"] != [NSNull null])
            view1.lbCuisine.text= [NSString stringWithFormat:@"菜系：%@",cuisineName];
        }
        else
        {
            NSString *areaName = [dic valueForKey:@"AREANAME"];
            view1.lbCuisine.text= [NSString stringWithFormat:@"商圈：%@",areaName];
        }
        if([dic valueForKey:@"ADDRESS"] != [NSNull null])
            view1.lbAddress.text= [NSString stringWithFormat:@"地址:%@",[dic valueForKey:@"ADDRESS"]];
        if([[dic valueForKey:@"DISCOUNT"] intValue]==10)
            view1.lbDiscount.text = @"无折扣";
        else
            view1.lbDiscount.text= [NSString stringWithFormat:@"%@折",[[dic valueForKey:@"DISCOUNT"] stringValue]];
        view1.lbTransport.text= [NSString stringWithFormat:@"公交线路：%@\n自驾线路：%@",
                                 [dic valueForKey:@"BUS_ROUTE"]==[NSNull null]?@"":[dic valueForKey:@"BUS_ROUTE"],[dic valueForKey:@"DRIVE_ROUTE"]==[NSNull null]?@"":[dic valueForKey:@"DRIVE_ROUTE"]];
//        view1.lbDrive.text= [NSString stringWithFormat:@"自驾线路：%@",[dic valueForKey:@"DRIVE_ROUTE"]];
        view1.lbMemo.text= [dic valueForKey:@"MEMO"]== [NSNull null]?@"":[dic valueForKey:@"MEMO"];
        view1.score =  [dic valueForKey:@"AVG_SCORE"] == [NSNull null]? [NSNumber numberWithFloat:0] : [NSNumber numberWithFloat:[[dic valueForKey:@"AVG_SCORE"] floatValue]];
        [view1.lbCuisine sizeToFit];
        view1.lbDistance.frame = CGRectMake(view1.lbDistance.frame.origin.x, view1.lbCuisine.frame.origin.y+[self calculateTextHeight :180 Content:view1.lbCuisine.text ]-2, 200, 20);
        view1.vPark.frame = CGRectMake(view1.vPark.frame.origin.x, view1.lbCuisine.frame.origin.y+[self calculateTextHeight :180 Content:view1.lbCuisine.text ]+20, 60, 20);
        view1.vBox.frame = CGRectMake(view1.vBox.frame.origin.x, view1.lbCuisine.frame.origin.y+[self calculateTextHeight :180 Content:view1.lbCuisine.text ]+20, 60, 20);
        [view1.lbAddress sizeToFit];
        [view1.lbTransport sizeToFit];
//        [view1.lbTransport sizeToFit];
        [view1.lbMemo sizeToFit];
        [view1.lbDiscount sizeToFit];
        [view1.lbPreference sizeToFit];
        view1.lbPreference.frame = CGRectMake(view1.lbDiscount.frame.origin.x+view1.lbDiscount.frame.size.width+2,view1.lbPreference.frame.origin.y,view1.lbPreference.frame.size.width,view1.lbPreference.frame.size.height);
        //动态调整控件y坐标
//        int y = view1.lbTransport.frame.origin.y+view1.lbTransport.frame.size.height;
//        view1.lbCanting.frame = CGRectMake(view1.lbCanting.frame.origin.x, y+5, view1.lbCanting.frame.size.width, view1.lbCanting.frame.size.height);
//        view1.lbLine.frame = CGRectMake(view1.lbLine.frame.origin.x, y+25, view1.lbLine.frame.size.width, view1.lbLine.frame.size.height);
//        view1.lbMemo.frame = CGRectMake(view1.lbMemo.frame.origin.x, y+30, view1.lbMemo.frame.size.width, view1.lbMemo.frame.size.height);
        [self setImageView:[[dic valueForKey:@"MERCHANT_ID"] intValue] withURL:[dic valueForKey:@"IMAGEPATH"]];
        
        CGFloat y1 ;
        if(view1.lbPreference.text.length<10)
            y1= [self calculateTextHeight :220 Content:view1.lbDiscount.text ];
        else
            y1= [self calculateTextHeight :220 Content:view1.lbPreference.text ];

        view1.vAddress.frame = CGRectMake(view1.vAddress.frame.origin.x,(view1.lbPreference.frame.origin.y+y1),view1.vAddress.frame.size.width,view1.vAddress.frame.size.height);
        y1= [self calculateTextHeight :268 Content:view1.lbAddress.text ];
        y1=y1<35?35:y1+8;
        view1.vbook.frame = CGRectMake(view1.vbook.frame.origin.x,(view1.vAddress.frame.origin.y+y1),view1.vbook.frame.size.width,view1.vbook.frame.size.height);
        
        view1.imageBus.frame = CGRectMake(view1.imageBus.frame.origin.x,view1.lbTransport.frame.origin.y,view1.imageBus.frame.size.width,view1.imageBus.frame.size.height);
        NSString *text =[NSString stringWithFormat:@"公交线路：%@",
                         [dic valueForKey:@"BUS_ROUTE"]==[NSNull null]?@"":[dic valueForKey:@"BUS_ROUTE"]];
        CGFloat y = [self calculateTextHeight :290 Content:text ];
        
        view1.imageCar.frame = CGRectMake(view1.imageCar.frame.origin.x,view1.lbTransport.frame.origin.y+y,view1.imageCar.frame.size.width,view1.imageCar.frame.size.height);
          int tranportHeight = view1.lbTransport.frame.size.height+view1.lbDrive.frame.size.height;
        BOOL bCard=[dic valueForKey:@"SETTING_ID"]!=nil;
        CGFloat CardHeight=0;
        CGFloat TopY=view1.vbook.frame.origin.y+40;
        if(bCard)
        {
            view1.vCard.frame=CGRectMake(view1.vTransport.frame.origin.x,view1.vbook.frame.origin.y+40,view1.frame.size.width,40);
            [view1.btnCard addTarget:self action:@selector(showCard) forControlEvents:UIControlEventTouchUpInside];
            settingID=[[dic valueForKey:@"SETTING_ID"] intValue];
            view1.lbCardInfo.text=[NSString stringWithFormat:@"会员卡：%@",[dic valueForKey:@"ECARD_DISCOUNT_INFO"]];
            view1.lbCardInfo.numberOfLines=0;
            [view1.lbCardInfo sizeToFit];
            CardHeight = [self calculateTextHeight :258 Content:view1.lbCardInfo.text ];
            view1.vCard.frame = CGRectMake(view1.vCard.frame.origin.x,view1.vCard.frame.origin.y,view1.frame.size.width,(CardHeight+20));
            TopY=view1.vCard.frame.origin.y+view1.vCard.frame.size.height;
        }
        else
        {
            view1.vCard.hidden=YES;
        }
        BOOL bCoupon;
        if(dic[@"IS_COUPON"]!=[NSNull null])
        {
            if([dic[@"IS_COUPON"] intValue]==1 && ([dic[@"MERCHANT_STATUS"] intValue]==1 || [dic[@"MERCHANT_STATUS"] intValue]==3 ))
            {
                bCoupon=YES;
            }
            else
            {
                bCoupon=NO;
            }
        }
        else
        {
            bCoupon=NO;
        }
        if(bCoupon)
        {
            view1.vTicket.hidden=NO;
            CGRect frame=view1.vTicket.frame;
            frame.origin.y=TopY;
            view1.vTicket.frame=frame;
            TopY+=view1.vTicket.frame.size.height;
            [view1.btnShowTicket addTarget:self action:@selector(showTicket) forControlEvents:UIControlEventTouchUpInside];
        }
        else
        {
            view1.vTicket.hidden=YES;
        }
        if(_merchantType==1)
        {
            view1.ImageDishExample.layer.masksToBounds=YES;
            [view1.ImageDishExample.layer setBorderColor:[[UIColor grayColor] CGColor]];
            [view1.ImageDishExample.layer setBorderWidth:0.5f];
            [view1.ImageDishExample.layer setCornerRadius:0];
            view1.vDish.frame=CGRectMake(view1.vTransport.frame.origin.x,TopY,view1.frame.size.width,82);
             view1.vTransport.frame = CGRectMake(view1.vTransport.frame.origin.x,view1.vDish.frame.origin.y+82,view1.frame.size.width,(tranportHeight+50));
            [view1.btnShowList addTarget:self action:@selector(btnShowDish) forControlEvents:UIControlEventTouchUpInside];
             [view1.btnShowMore addTarget:self action:@selector(btnShowDish) forControlEvents:UIControlEventTouchUpInside];
        }
        else
        {
            view1.vDish.hidden=YES;
             view1.vTransport.frame = CGRectMake(view1.vTransport.frame.origin.x,TopY,view1.frame.size.width,(tranportHeight+50));
        }
        view1.vComment.frame = CGRectMake(view1.vComment.frame.origin.x,(view1.vTransport.frame.origin.y+tranportHeight+10),view1.vComment.frame.size.width,view1.vComment.frame.size.height);
        view1.vMemo.frame = CGRectMake(view1.vMemo.frame.origin.x,(view1.vTransport.frame.origin.y+tranportHeight+50),view1.vMemo.frame.size.width,view1.vMemo.frame.size.height);
        //计算页面高度
//        [view1.svMain setContentSize:CGSizeMake(320, 280+y+y1+tranportHeight+[self calculateTextHeight :310 Content:view1.lbMemo.text ])];
        int svHeight = 280+y1+40+40+[self calculateTextHeight :280 Content:view1.lbTransport.text ]+[self calculateTextHeight :310 Content:view1.lbMemo.text ]+(_merchantType==1?82:0)+(bCard?view1.vCard.frame.size.height:0)+(bCoupon?view1.vTicket.frame.size.height:0);
        //NSLog(@"%d",svHeight);
        [view1.svMain setContentSize:CGSizeMake(320,svHeight)];
        if([dic[@"MERCHANT_STATUS"] intValue]!=1 && [dic[@"MERCHANT_STATUS"] intValue]!=3)
        {
            _btnBook.enabled=NO;
        }
        else
        {
            _btnBook.enabled=YES;
        }
//        view1.vComment.hidden=true;
        //地图页面
        if([dic valueForKey:@"LATITUDE"] != [NSNull null]){
            //为地图添加注解
            CLLocationCoordinate2D coordinate = {[[dic valueForKey:@"LATITUDE"] floatValue], [[dic valueForKey:@"LONGTITUDE"] floatValue]};
            float zoomLevel =0.15; //设置显示精度
            //确定显示初始位置
            MKCoordinateRegion region =MKCoordinateRegionMake(coordinate, MKCoordinateSpanMake(zoomLevel, zoomLevel));
            MKCoordinateRegion adjustedRegion = [view3.map regionThatFits:region];
            [view3.map setRegion:adjustedRegion animated:YES];
            [view3.map setCenterCoordinate:coordinate zoomLevel:11 animated:NO];
            view3.map.centerCoordinate = coordinate;
            ASPin *pin =[[ASPin alloc]initWithCoordinate:coordinate];
            pin.tips = [dic valueForKey:@"NAME"];
            [view3.map addAnnotation: pin];
           
        }
        //评论页面
//        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?merchantID=%d",url_commentList,_merchantId]] ;
//        request = [ASIHTTPRequest requestWithURL:url];
//        [request startSynchronous];
//        
//        NSString *jsonStr = [request responseString];
//        
//        NSDictionary *dic = [jsonStr JSONValue];
//        tableDataArray = [dic valueForKey:@"data"];
//        [view2.tbComment reloadData];
//        [Config setExtraCellLineHidden:view2.tbComment];
//        NSLog(@"%@",tableDataArray);
    }else{
        [OMGToast showWithText:@"商户信息错误。" bottomOffset:100];
        [self.navigationController popViewControllerAnimated:YES];
    }
}
-(CGFloat)calculateTextHeight:(CGFloat)widthInput Content:(NSString *)strContent{
    CGSize constraint = CGSizeMake(widthInput, 20000.0f);
    CGSize size = [strContent sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
    //CGFloat height = MAX(size.height, 44.0f);
    return size.height;
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    isSearchFinished = true;
    isCommentFinished = true;
    isSearchMoreFinished = true;
    NSError *error = [request error];
    NSLog(@"%@",error);
    if (error.code==net_failure_code) {
        [OMGToast showWithText:net_failure_msg bottomOffset:100];
        btBack.userInteractionEnabled = true;
    }
}
- (void)setImageView:(int) id withURL:(NSString *) imagePath{
    //?inputPath=
    NSString *imageStr = [NSString stringWithFormat:@"%@%@",url_image,imagePath];
    //        NSLog(@"%@",imageStr);
//    NSString *imageName = [NSString stringWithFormat:@"%d%@",id,@".temp"];
    NSString *imageName =@"";
    if (![imagePath isEqual:[NSNull null] ]) {
        NSArray *array = [imageStr componentsSeparatedByString:@"/"];
        imageName = [array lastObject];
    }
//    NSLog(@"%@",imageName);
    if(imageName){
        NSString *imageDataPath = [NSHomeDirectory() stringByAppendingPathComponent:[@"Library/Caches/" stringByAppendingString:imageName]];
        
        if (![[NSFileManager defaultManager] fileExistsAtPath:imageDataPath]) {
            
            NSURL *imageUrl = [NSURL URLWithString:[imageStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
            NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
            [imageData writeToFile:imageDataPath atomically:YES];
            UIImage *image = [UIImage imageWithData:imageData];
            if(image)
            {
                [view1.imageView setImage:image];
            }
            else
            {
                [view1.imageView setImage:[UIImage imageNamed:@"placeholder.png"]];
            }
        }else{
            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfFile:imageDataPath]];
            if (image) {
                [view1.imageView setImage:image];
            }
            else
            {
                image = [UIImage imageNamed:@"placeholder.png"];
                //placeholder为在未加载完成加载图片时显示的默认图片
                [view1.imageView setImage:image];
            }
            
        }
    }

}

- (IBAction)doBack:(id)sender {
    if([_lbTitle.text isEqualToString:TITLE_DETAIL]){
        if(!isSearchFinished){
            [reqSearch clearDelegatesAndCancel];
            [reqSearch cancel];
        }
        if(!isCommentFinished){
            [reqComment clearDelegatesAndCancel];
            [reqComment cancel];
        }
        view3.map.delegate=nil;
        
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        _lbTitle.text = TITLE_DETAIL;
        [self btnRestaurantAction];
    }
}
- (void) addBasicView
{
    btnRestaurant.showsTouchWhenHighlighted = YES;  //指定按钮被按下时发光
    [btnRestaurant setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];//此时选中
    [btnRestaurant addTarget:self action:@selector(btnRestaurantAction) forControlEvents:UIControlEventTouchUpInside];
    btnRemark.showsTouchWhenHighlighted = YES;  //指定按钮被按下时发光
    [btnRemark setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];//此时未被选中
    [btnRemark addTarget:self action:@selector(btnRemarkAction) forControlEvents:UIControlEventTouchUpInside];
    
    btnMap.showsTouchWhenHighlighted = YES;  //指定按钮被按下时发光
    [btnMap setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];//此时未被选中
    [btnMap addTarget:self action:@selector(btnMapAction) forControlEvents:UIControlEventTouchUpInside];
    sliderLabel.frame = CGRectMake(1, IS_IPHONE_5?80:74, 120, 2);

}

#pragma mark-
#pragma mark 界面按钮事件

- (void) btnActionShow
{
    if (currentPage == 0) {
        [self btnRestaurantAction];
    }
    else if (currentPage == 1) {
        [self btnRemarkAction];
    }
    else if (currentPage == 2) {
        [self btnMapAction];
    }
}
-(void)btnShowDish
{
    if(view1.ImageDishExample.hidden==YES)
    {
        DishListViewContrller *view=[[DishListViewContrller alloc] initWithNibName:@"DishListViewContrller" bundle:nil];
        view.merchantId=_merchantId;
        [self.navigationController pushViewController:view animated:YES];
    }
    else
    {
        UpdateHeaderViewController *view=[[UpdateHeaderViewController alloc] initWithNibName:@"UpdateHeaderViewController" bundle:nil];
        view.merchantID=_merchantId;
        [self.navigationController pushViewController:view animated:YES];
    }
}

- (void) btnRestaurantAction
{
//    [btnRestaurant setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];//此时选中
//    [btnRemark setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];//此时未被选中
//    [btnMap setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];//此时未被选中
//    UIImage *im = [UIImage imageNamed:@"ic_detail_comment"];
//    [btnRemark setImage:im forState:UIControlStateNormal];
//    im = [UIImage imageNamed:@"ic_detail_base_selected"];
//    [btnRestaurant setImage:im forState:UIControlStateNormal];
//    im = [UIImage imageNamed:@"ic_detail_transport"];
//    [btnMap setImage:im forState:UIControlStateNormal];

    [RestaurantView beginAnimations:nil context:nil];//动画开始
    [RestaurantView setAnimationDuration:0.3];
    
//    sliderLabel.frame = CGRectMake(1, IS_IPHONE_5?80:74, 120, 2);
    [svMain setContentOffset:CGPointMake(320*0, 0)];//页面滑动
    
    [RestaurantView commitAnimations];
}

- (void) btnRemarkAction
{
    [btnRemark setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];//此时选中
    [btnRestaurant setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];//此时未被选中
    [btnMap setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];//此时未被选中

    UIImage *im = [UIImage imageNamed:@"ic_detail_comment_selected"];
    [btnRemark setImage:im forState:UIControlStateNormal];
    im = [UIImage imageNamed:@"ic_detail_base"];
    [btnRestaurant setImage:im forState:UIControlStateNormal];
    im = [UIImage imageNamed:@"ic_detail_transport"];
    [btnMap setImage:im forState:UIControlStateNormal];

    [CommentView beginAnimations:nil context:nil];//动画开始
    [CommentView setAnimationDuration:0.3];
    
//    sliderLabel.frame = CGRectMake(106,IS_IPHONE_5?80:74, 120, 2);
    [svMain setContentOffset:CGPointMake(320*1, 0)];
    
    [CommentView commitAnimations];
    _lbTitle.text=@"会员点评";
    if (tableDataArray.count==0) {
        [OMGToast showWithText:@"没有相关信息。" bottomOffset:50];
    }
}
- (void) btnMapAction
{
    [btnMap setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];//此时选中
    [btnRemark setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];//此时未被选中
    [btnRestaurant setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];//此时未被选中
    UIImage *im = [UIImage imageNamed:@"ic_detail_comment"];
    [btnRemark setImage:im forState:UIControlStateNormal];
    im = [UIImage imageNamed:@"ic_detail_base"];
    [btnRestaurant setImage:im forState:UIControlStateNormal];
    im = [UIImage imageNamed:@"ic_detail_transport_selected"];
    [btnMap setImage:im forState:UIControlStateNormal];

    [MapView beginAnimations:nil context:nil];//动画开始
    [MapView setAnimationDuration:0.3];
    
//    sliderLabel.frame = CGRectMake(212, IS_IPHONE_5?80:74, 120, 2);
    [svMain setContentOffset:CGPointMake(320*2, 0)];
    
    [MapView commitAnimations];
    _lbTitle.text=view1.lbName.text;

}

- (IBAction)doShareSMS:(id)sender {
    NSURL *url = [NSURL URLWithString:url_shareSMS];
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
    [request setPostValue:[NSString stringWithFormat:@"%d",_merchantId] forKey:@"merchantID"];
    [request setPostValue:[NSString stringWithFormat:@"%d",_merchantType] forKey:@"merchantType"];
    [request startSynchronous];
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
//    NSLog(@"%@",dic);
    if([[dic valueForKey:@"status"] isEqualToString:@"SUCCESS"])
    {
//        UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示"
//                                                      message:[dic valueForKey:@"data"]
//                                                     delegate:nil
//                                            cancelButtonTitle:@"确定"
//                                            otherButtonTitles:nil];
//        [alert show];
//        [alert release];
        NSString *str;
        if(_merchantType==1)
        {
            str=@"不错的餐馆";
        }
        else if(_merchantType==2)
        {
            str=@"不错的KTV";
        }
        else
        {
            str=@"不错的咖啡茶馆";
        }
       [self sendSMS:[[dic valueForKey:@"data"] stringByReplacingOccurrencesOfString:@"不错的餐馆" withString:str] recipientList:nil];


    }

}
//调用sendSMS函数
//内容，收件人列表
- (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSArray *)recipients
{
    
    MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
    
    if([MFMessageComposeViewController canSendText])
        
    {
        
        controller.body = bodyOfMessage;
        
//        controller.recipients = recipients;
        
        controller.messageComposeDelegate = self;
//        [self.navigationController pushViewController:controller animated:YES];
        [self presentModalViewController:controller animated:YES];
    }
    
}

// 处理发送完的响应结果
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    [self dismissModalViewControllerAnimated:YES];
    
    if (result == MessageComposeResultCancelled)
        NSLog(@"Message cancelled");
    else if (result == MessageComposeResultSent)
        NSLog(@"Message sent") ;
    else 
        NSLog(@"Message failed") ;
}
    
- (IBAction)doAddFavorite:(id)sender {
    int memberId = [[Config Instance] getMemberId];
    //判断是否登录会员
    if(memberId == 0)
    {
        UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示"
                                                      message:@"您还未登录，请先登录。"
                                                     delegate:nil
                                            cancelButtonTitle:@"确定"
                                            otherButtonTitles:nil];
        [alert show];
        
        LoginViewController  *view = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
        view.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:view animated:YES];
        return;
    }
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?merchantID=%d&merchantTypeID=%d&memberID=%d&password=%@",url_addFavorite,_merchantId,_merchantType,memberId,[[Config Instance] getPassword]]];
    ASIHTTPRequest *request=[ASIHTTPRequest requestWithURL:url];
//    [request setPostValue:[NSString stringWithFormat:@"%d",memberId] forKey:@"memberID"];
//    [request setPostValue:[[Config Instance] getPassword] forKey:@"password"];
//    [request setPostValue:[NSString stringWithFormat:@"%d",_merchantId] forKey:@"merchantID"];
//    [request setPostValue:[NSString stringWithFormat:@"%d",_merchantType] forKey:@" merchantTypeID"];
    [request startSynchronous];
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    //    NSLog(@"%@",dic);
    NSString *msg = @"";
    if([[dic valueForKey:@"status"] isEqualToString:@"SUCCESS"])
    {
        msg = @"收藏成功";
    }
    else
    {
        msg = [dic valueForKey:@"log"];
    }
    
    UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示"
                                                 message:msg
                                        delegate:nil
                                        cancelButtonTitle:@"确定"
                                       otherButtonTitles:nil];
    [alert show];
    
}

- (IBAction)doBook:(id)sender {
    [self doBookAction];
}

#pragma mark 左右滑动相关函数

- (void)initScrollView {
    
    //设置 tableScrollView
    // a page is the width of the scroll view
    svMain.pagingEnabled = YES;
    svMain.clipsToBounds = NO;
//    svMain.contentSize = CGSizeMake(svMain.frame.size.width *3, svMain.frame.size.height);
    svMain.showsHorizontalScrollIndicator = NO;
    svMain.showsVerticalScrollIndicator = NO;
//    svMain.scrollsToTop = NO;
    svMain.delegate = self;
//    [svMain setContentSize:CGSizeMake(320*3, 920)];

    [svMain setContentOffset:CGPointMake(0, 0)];
//    UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"img_bg_background.png"]];
//    svMain.backgroundColor = background; [background release];

    //公用
    currentPage = 0;
    pageControl.numberOfPages = 3;
    pageControl.currentPage = 0;
    pageControl.backgroundColor = [UIColor whiteColor];
    [self createAllEmptyPagesForScrollView];
}

- (void)createAllEmptyPagesForScrollView {
    
    NSArray *arr = [[NSBundle mainBundle] loadNibNamed:@"RestaurantView" owner:nil options:nil];
    view1 = (RestaurantView *)[arr objectAtIndex:0];
    view1.frame = CGRectMake(320*0, 0, 320, svMain.frame.size.height);
    if(_merchantType!=1)
    {
        _lbAvgConsume.hidden=YES;
    }
    view1.lbName.text=@"";
    [view1.btnBook addTarget:self action:@selector(doBookAction) forControlEvents:UIControlEventTouchUpInside];
    [view1.btnPhone addTarget:self action:@selector(doPhoneAction) forControlEvents:UIControlEventTouchUpInside];
//    [view1.svMain setContentSize:CGSizeMake(320, svMain.frame.size.height)];
//    [view1.svMain setContentOffset:CGPointMake(0, -100)];
    //显示评论列表
    [view1.btnComments addTarget:self action:@selector(btnRemarkAction) forControlEvents:UIControlEventTouchUpInside];
    //显示地图
    [view1.btnAddress addTarget:self action:@selector(btnMapAction) forControlEvents:UIControlEventTouchUpInside];

    [svMain addSubview: view1];
    
    arr = [[NSBundle mainBundle] loadNibNamed:@"CommentView" owner:nil options:nil];
    view2 = (CommentView *)[arr objectAtIndex:0];
    view2.frame = CGRectMake(320*1, 0, 320, svMain.frame.size.height);
    view2.tbComment.delegate = self;
    view2.tbComment.dataSource = self;
    [svMain addSubview: view2];
    
//    CGRect webFrame = CGRectMake(320*2,0.0,320.0,svMain.frame.size.height);
    //webFrame.origin.y+=25;
    arr = [[NSBundle mainBundle] loadNibNamed:@"MapView" owner:nil options:nil];
    view3 = (MapView *)[arr objectAtIndex:0];
    view3.frame = CGRectMake(320*2, 0, 320, svMain.frame.size.height);
//    view3 = [[UIWebView alloc] initWithFrame:webFrame];
//    [view3 setBackgroundColor:[UIColor whiteColor]];//设置北京为白色
//    view3.scalesPageToFit = YES;//适应屏幕大小
    //设置地图代理
    view3.map.delegate =self;
    //确定地图类型
    view3.map.mapType =MKMapTypeStandard;
//    view3.map.showsUserLocation =YES;

    [svMain addSubview: view3];
    
}

// 评论列表设置
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	int count = [tableDataArray count];
    if (count>=pageSize) {
        return count+1;
    }else
        return count;
    return count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([indexPath row] < ([tableDataArray count])) {
        NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
        if([item valueForKey:@"REPLY"]!=[NSNull null])
        {
            return 150;
        }
        else
        {
            return 110;
        }
    }else{
        return 40;
    }
}
- (CGFloat)tableView:(UITableView *)tableView widthForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 320;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"CommentCellIdentifier";
    if([indexPath row] < ([tableDataArray count])) {

    CommentCell *cell = (CommentCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
    NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"CommentCell" owner:nil options:nil];
    cell = [array objectAtIndex:0];
    [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
            }
    
    NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
    NSString *name = @"";
    if([item valueForKey:@"NICKNAME"] == [NSNull null] && [item valueForKey:@"MOBILE"] != [NSNull null])
    {
        NSMutableString * mobile = [NSMutableString stringWithString:[item valueForKey:@"MOBILE"]];
        [mobile replaceCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
        name = mobile;
        
    }else
        name = [item valueForKey:@"NICKNAME"]==[NSNull null]?@"":[item valueForKey:@"NICKNAME"];
    cell.lbNickName.text = name;
    cell.lbScore1.text = [NSString stringWithFormat:@"%@",[item valueForKey:@"环境"]];
    cell.lbScore2.text = [NSString stringWithFormat:@"%@",[item valueForKey:@"交通"]];
    cell.lbScore3.text =  [NSString stringWithFormat:@"%@",[item valueForKey:@"菜肴"]];
    cell.score = [item valueForKey:@"AGREE"] == [NSNull null]? [NSNumber numberWithFloat:0] : [NSNumber numberWithFloat:[[item valueForKey:@"AGREE"] floatValue]];
    cell.lbContent.text=[item valueForKey:@"CONTENT"];
    if([item valueForKey:@"REPLY"]!=[NSNull null])
    {
        cell.lbReply.text=[[NSString alloc] initWithFormat:@"商户回复:%@",[item valueForKey:@"REPLY"]];
    }
    else
    {
        cell.lbReply.text=@"";
    }

    return cell;
    }else{
        LoadMoreCell *cell = (LoadMoreCell *)[tableView dequeueReusableCellWithIdentifier: @"LoadMoreCellIdentifier"];
        if (cell==nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"LoadMoreCell" owner:nil options:nil];
            cell = [array objectAtIndex:0];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        if(returnCount<pageSize){
            cell.lbText.text=@"";
            cell.hidden = true;
        }else{
            //创建loadMoreCell
            cell.lbText.text=str_more;
        }
        cell.textLabel.textAlignment = UITextAlignmentCenter;
        cell.detailTextLabel.text=@"";
        cell.imageView.image =nil;
        return cell;
        
    }

}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == [tableDataArray count]) {
        LoadMoreCell *loadMoreCell=(LoadMoreCell *)[tableView cellForRowAtIndexPath:indexPath];
        loadMoreCell.lbText.text=str_loading;
        //        [self performSelectorInBackground:@selector(loadMore) withObject:nil];
        //        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?merchantID=%d&pageIndex=%d&merchantType=%d",url_commentList,_merchantId,++pageIndex,_merchantType]] ;
        reqSearchMore = [ASIFormDataRequest requestWithURL:url];
        [reqSearchMore setDidFinishSelector:@selector(appendTableWith:)];
        [reqSearchMore setShouldAttemptPersistentConnection:NO];
        reqSearchMore.delegate = self;
        isSearchMoreFinished = false;
        [reqSearchMore startAsynchronous];
        return;
    }else{
        //传递商户id参数
    NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"点评内容"
                                                   message:[NSString stringWithFormat:@"%@\n\n%@", [item objectForKey:@"CONTENT"],[item objectForKey:@"REPLY"]!=[NSNull null]?[NSString stringWithFormat:@"商户回复：%@", [item objectForKey:@"REPLY"]]:@""]
                                    delegate:nil
                                    cancelButtonTitle:@"确定"
                                    otherButtonTitles:nil];
 //   ((UILabel*)[[alert subviews] objectAtIndex:1]).textAlignment = UITextAlignmentLeft;
//    alert.bgImage = [UIImage imageNamed:@"image_title.png"];
//    alert.detailTextlAligment = UITextAlignmentLeft;
    [alert show];

    }
    //其他cell的事件
    
}
-(void) appendTableWith:(ASIHTTPRequest *)request
{   //将loadMore中的NSMutableArray添加到原来的数据源listData中.
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    NSMutableArray *data = [dic valueForKey:@"data"];
    returnCount = [data count];
    //    [self performSelectorOnMainThread:@selector(appendTableWith:) withObject:array waitUntilDone:NO];
    for (int i=0;i<[data count];i++) {
        [tableDataArray addObject:[data objectAtIndex:i]];
    }
    NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:pageSize];
    for (int ind = 0; ind < [data count]; ind++) {
        NSIndexPath    *newPath =  [NSIndexPath indexPathForRow:[tableDataArray indexOfObject:[data objectAtIndex:ind]] inSection:0];
        [insertIndexPaths addObject:newPath];
    }
    //重新调用UITableView的方法, 来生成行.
    [view2.tbComment insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
    isSearchMoreFinished = true;
}
-(void) doBookAction{
    if(merchant==nil)
    {
        [OMGToast showWithText:net_failure_msg bottomOffset:100];
        return;
    }
    if([[merchant valueForKey:@"IS_AGREEMENT"] intValue]==0)
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:APP_TITLE
                                                         message:MSG_NOT_AGREEMENT
                                                        delegate:nil
                                               cancelButtonTitle:@"确定"
                                               otherButtonTitles:nil];
        //    alert.bgImage = [UIImage imageNamed:@"image_title.png"];
//        alert.detailTextlAligment = UITextAlignmentLeft;
      //  ((UILabel*)[[alert subviews] objectAtIndex:1]).textAlignment = UITextAlignmentLeft;
        [alert show];
        return;
    }

    BookViewController  *view = [[BookViewController alloc] initWithNibName:@"BookViewController" bundle:nil];
    //传递商户id参数
    view.merchantType=_merchantType;
    view.merchantId = _merchantId;
    view.merchantName = view1.lbName.text ;
    if([[merchant valueForKey:@"IS_BOX"] intValue]==1)
        view.showBox = true;
    else
        view.showBox = false;
    view.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:view animated:YES];
    //        [view release];

}
-(void) doPhoneAction{
//    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://4000509177"]];
//    NSLog(@"%@",@"4000509177");
    NSURL *phoneURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",CALL_NUMBER]];
    if ( !phoneCallWebView ) {
        phoneCallWebView = [[UIWebView alloc] initWithFrame:CGRectZero];
    }
    [phoneCallWebView loadRequest:[NSURLRequest requestWithURL:phoneURL]];
    
}
// At the end of scroll animation, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    CGFloat pageWidth = self.svMain.frame.size.width;
    int page = floor((self.svMain.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    
    pageControl.currentPage = page;
    currentPage = page;
    pageControlUsed = NO;
    [self btnActionShow];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    //暂不处理 - 其实左右滑动还有包含开始等等操作，这里不做介绍
}

- (BOOL)touchesShouldBegin:(NSSet *)touches withEvent:(UIEvent *)event inContentView:(UIView *)view
{
    return YES;
}
- (BOOL)touchesShouldCancelInContentView:(UIView *)view
{
    return NO;
}

#pragma mark - MKMapViewDelegate

//添加注解
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:( id <MKAnnotation>)annotation
{
    if([annotation isKindOfClass:[MKUserLocation class]])
        return nil;
    MKPinAnnotationView *pinView =nil;
    static NSString *defaultPinID =@"AS.PIN";
    
    
    pinView = (MKPinAnnotationView *)[view3.map dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
    if(pinView==nil)
    {
        pinView = [[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:defaultPinID];
        
        pinView.canShowCallout =YES; //是否点击显示注释文字
        pinView.animatesDrop =NO;
        
    }
    return pinView;
    
}

-(void) showCard
{
    CardDetailViewController *view=[[CardDetailViewController alloc] initWithNibName:@"CardDetailViewController" bundle:nil];
    view.hidesBottomBarWhenPushed=YES;
    view.settingID=settingID;
    view.ParView=self.view;
    [self.navigationController pushViewController:view animated:YES];

}

-(void)showTicket
{
    TicketMerchantViewController *view=[[TicketMerchantViewController alloc] initWithNibName:@"TicketMerchantViewController" bundle:nil];
    view.hidesBottomBarWhenPushed=YES;
    view.MerchantId=_merchantId;
    view.MerchantType=_merchantType;
    view.MerchantName=view1.lbName.text;
    [self.navigationController pushViewController:view animated:YES];

}

- (void)dealloc {
    phoneCallWebView = nil;
}
@end
